package com.magic_bag;


import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.nio.ByteBuffer;

/**
 * @ClassName: MagicBag
 * @Author: ZhangYue26
 * @Description: java发送魔术包 诗选远程开机 详情见：TODO https://blog.csdn.net/u013363811/article/details/44343437/
 *              就是说魔术包是由12个“F”加重复16次的主机MAC地址组成
 *              MAC地址为： “28-D2-44-35-68-A7
 *              则魔术包为： 0xFFFFFFFFFFFF28D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A728D2443568A7
 * @Date: 2020-11-03
 */
public class MagicBag {

    public static void main(String[] args) {
        sendMagicBag("10.195.158.255","EC-5C-68-DC-F4-87",9);
    }


    public static void sendMagicBag(String broadcastAddress, String MAC, int port) {
        String head = "FFFFFFFFFFFF";
        StringBuffer magicBagBuffer = new StringBuffer();
        for (int i = 0; i < 16; i++) {
            magicBagBuffer.append(MAC.replaceAll("-", ""));
        }
        String magicBag = head + magicBagBuffer.toString();//魔术包16进制字符串
        byte[] bytes = hexStr2Byte(magicBag);

        try {
            InetAddress inetAddress = InetAddress.getByName(broadcastAddress);
            MulticastSocket multicastSocket = new MulticastSocket(port);
            DatagramPacket packet = new DatagramPacket(bytes, bytes.length, inetAddress, port);
            multicastSocket.send(packet);
            multicastSocket.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
      * @Description 16进制字符串转字节数组
      * @author ZhangYue26
      * @date 2020/11/3
      * @param [hex]
      * @return byte[]
      **/
    public static byte[] hexStr2Byte(String hex) {
        ByteBuffer bf = ByteBuffer.allocate(hex.length() / 2);
        for (int i = 0; i < hex.length(); i++) {
            String hexStr = hex.charAt(i) + "";
            i++;
            hexStr += hex.charAt(i);
            byte b = (byte) Integer.parseInt(hexStr, 16);
            bf.put(b);
        }
        return bf.array();
    }


}
